export const RdcRuleMixin = {
  props: { value: '', ruleType: '' },
  data() {
    return {
      initItem: {},
      addBtn: true,
      isUnlimitMax: false,
      form: {
        list: [{ ...this.initItem }]
      },
      rules: {
        range: [
          {
            validator: (rule, val, cb) => {
              const index = +rule.field.split('.')[1]
              const list = this.form.list
              const item = list[index]
              const min = item.min || 0
              const max = item.max || 0
              if (index > 0) {
                const preItem = list[index - 1]
                const preMax = preItem.max || 0
                if (min <= preMax) return cb('最小值应大于前一项的最大值')
              }

              // 最后一项，且设置了不限最大值
              if (index === list.length - 1 && this.isUnlimitMax) return cb()

              if (max < min) return cb('最大值不能小于最小值')
              cb()
            }
          }
        ],
        level: [{ required: true, message: '请选择等级' }]
      }
    }
  },
  computed: {
    ruleJson: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    ruleJson: {
      handler(val) {
        const initVal = { ...this.initItem }
        try {
          val = JSON.parse(val)
          if (!Array.isArray(val) || !val.length) return (this.form.list = [initVal])

          const keys = Object.keys(initVal)
          // 重组字段
          let arr = val.map(i => keys.reduce((o, k) => !void (o[k] = i[k] || initVal[k]) && o, {}))

          if (this.addBtn) {
            // 有多项，且最后一项为空字符串，表示设置了不限最大值
            const last = val.at(-1)
            if (last.max === '') {
              arr[arr.length - 1].max = ''
              this.isUnlimitMax = true
            }
          } else {
            // 无 addBtn 则只有一项
            arr = arr.slice(0, 1)
          }
          this.form.list = arr
        } catch (error) {
          this.form.list = [initVal]
        }
      },
      immediate: true
    }
  },
  methods: {
    async validate() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return false
      this.$emit('input', JSON.stringify(this.form.list))
      return true
    },
    async addItem() {
      const valid = await this.$refs.form.validate().catch(() => false)
      if (!valid) return
      this.form.list.push({ ...this.initItem })
      // 滚动到最右边
      const el = this.$refs.form?.$el || this.$refs.form
      this.$nextTick(() => (el.scrollLeft = el.scrollWidth))
    },
    onUnlimitMax() {
      this.isUnlimitMax = true
      const list = this.form.list
      const last = list.at(-1)
      last.max = ''
      this.form.list[list.length - 1] = last
      this.$refs.form.validateField(`list.${list.length - 1}.min`)
    },
    cancelUnlimitMax() {
      this.isUnlimitMax = false
      const list = this.form.list
      const last = list.at(-1)
      last.max = last.min
      this.form.list[list.length - 1] = last
    }
  }
}

export default RdcRuleMixin
